//
//  HunterDB.m
//  eye_hunter
//
//  Created by cherry on 10-9-26.
//  Copyright 2010 __MyCompanyName__. All rights reserved.
//

#import "HunterDB.h"
#import "HunterTool.h"

@implementation HunterDB

@synthesize databaseName;
@synthesize databasePath;

-(void) checkAndInitDatabase{
	// Check if the SQL database has already been saved to the users phone, if not then copy it over
	BOOL success;
	
	// Create a FileManager object, we will use this to check the status
	// of the database and to copy it over if required
	NSFileManager *fileManager = [NSFileManager defaultManager];
	
	// Check if the database has already been created in the users filesystem
	success = [fileManager fileExistsAtPath:databasePath];
	
	// If the database already exists then return without doing anything
	if(success) return;
	
	// If not then proceed to copy the database from the application to the users filesystem
	
	// Get the path to the database in the application package
	NSString *databasePathFromApp = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:databaseName];
	
	// Copy the database from the package to the users filesystem
	[fileManager copyItemAtPath:databasePathFromApp toPath:databasePath error:nil];
	
	[fileManager release];
}

-(void) initDB{
	// init databaseName
	databaseName = @"eye_hunter_v0.db";
	// Get the path to the documents directory and append the databaseName
	NSArray *documentPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
	NSString *documentsDir = [documentPaths objectAtIndex:0];
	databasePath = [documentsDir stringByAppendingPathComponent:databaseName];
	
	[self checkAndInitDatabase];
}

-(NSMutableArray *) findAllMissions{
	sqlite3 *database;
	NSMutableArray *missions = [[NSMutableArray alloc] init];
	
	//Open Database
	if (sqlite3_open([databasePath UTF8String], &database) == SQLITE_OK) {
		const char *sqlStatement = "select * from pic_mission";
		sqlite3_stmt *compiledStatement;
		if(sqlite3_prepare_v2(database, sqlStatement, -1, &compiledStatement, NULL) == SQLITE_OK) {
			// Loop through the results and add them to the feeds array
			while(sqlite3_step(compiledStatement) == SQLITE_ROW) {
				//Read data
				int mid = (int)sqlite3_column_int(compiledStatement, 0);
				NSString *pic = [NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 1)];
				//create TopRecord
				PicMission *mission	= [[PicMission alloc] initById:mid andPic:pic];
				[missions addObject:mission];
			}
		}
		// Release the compiled statement from memory
		sqlite3_finalize(compiledStatement);
	}
	sqlite3_close(database);
	
	return missions;
}

-(NSMutableArray *) findAllTargetInMission: (int) missionId{
	sqlite3 *database;
	NSMutableArray *targets = [[NSMutableArray alloc] init];
	
	//Open Database
	if (sqlite3_open([databasePath UTF8String], &database) == SQLITE_OK) {
		NSString *sql = [[NSString alloc] initWithFormat:@"select * from pic_target t where t.mid=%i",missionId];
		const char *sqlStatement = [sql UTF8String];
		sqlite3_stmt *compiledStatement;
		if(sqlite3_prepare_v2(database, sqlStatement, -1, &compiledStatement, NULL) == SQLITE_OK) {
			// Loop through the results and add them to the feeds array
			while(sqlite3_step(compiledStatement) == SQLITE_ROW) {
				//Read data
				int tid = (int)sqlite3_column_int(compiledStatement, 0);
				NSString *dust_pic = [NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 2)];
				NSString *light_pic = [NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 3)];
				int minX = (int)sqlite3_column_int(compiledStatement, 4);
				int minY = (int)sqlite3_column_int(compiledStatement, 5);
				int maxX = (int)sqlite3_column_int(compiledStatement, 6);
				int maxY = (int)sqlite3_column_int(compiledStatement, 7);
				//create TopRecord
				PicTarget *target = [[PicTarget alloc] init];
				[target setTargetId:tid];
				[target setMissionId:missionId];
				[target setMinX:minX];
				[target setMinY:minY];
				[target setMaxX:maxX];
				[target setMaxY:maxY];
				[target setDustPic:dust_pic];
				[target setLightPic:light_pic];
                [target setIsFound:NO];
				[targets addObject:target];
			}
		}
		// Release the compiled statement from memory
		sqlite3_finalize(compiledStatement);
	}
	sqlite3_close(database);
	
	return targets;
}

-(NSMutableArray *) findRandomMissions:(int) count{
	NSMutableArray *missions = [self findAllMissions];
	if ([missions count] <= count) {
		return missions;
	}
	NSMutableArray *ids = [HunterTool randomIntArray:[missions count] count:count];
	NSMutableArray *result = [[NSMutableArray alloc] init];
	for (NSNumber *number in ids) {
		[result addObject:[missions objectAtIndex:[number intValue]]];
	}
	[missions dealloc];
	[ids dealloc];
	
	return result;
}

-(NSMutableArray *) findRandom:(int) count targetsInMission:(int) missionId{
	NSMutableArray *targets = [self findAllTargetInMission:missionId];
	if ([targets count] <= count) {
		return targets;
	}
	NSMutableArray *ids = [HunterTool randomIntArray:[targets count] count:count];
	NSMutableArray *result = [[NSMutableArray alloc] init];
	for (NSNumber *number in ids) {
		[result addObject:[targets objectAtIndex:[number intValue]]];
	}
	[targets dealloc];
	[ids dealloc];
	
	return result;
}
@end
